<template>
  <div>

<!-- 页面头部组件，带有返回按钮，点击时调用goBack方法，显示内容为"课程管理" -->  
<el-page-header @back="goBack" content="课程管理"></el-page-header>  
  
<!-- 标签页组件，标签位置由tabPosition变量控制，高度自适应 -->  
<el-tabs :tab-position="tabPosition" style="height: auto;">  
  
  <!-- 第一个标签页，标签为"收藏的课程" -->  
  <el-tab-pane label="收藏的课程">  
    <!-- 表格组件，展示收藏的课程数据，宽度100% -->  
    <el-table :data="courses1" style="width: 100%">  
      <!-- 课程分类列 -->  
      <el-table-column prop="categoryName" label="课程分类"></el-table-column>  
      <!-- 课程名称列 -->  
      <el-table-column prop="courseName" label="课程名称"></el-table-column>  
      <!-- 课程教师列 -->  
      <el-table-column prop="lecturerName" label="课程教师"></el-table-column>  
      <!-- 课程简介列 -->  
      <el-table-column prop="introduce" label="课程简介"></el-table-column>  
      <!-- 价格列 -->  
      <el-table-column prop="coursePrice" label="价格(元)"></el-table-column>  
      <!-- 操作列，包含观看课程和取消收藏两个按钮 -->  
      <el-table-column label="操作" width="120">  
        <template slot-scope="scope">  
          <!-- 观看课程按钮，点击时调用SeeCourse方法，传入课程和索引 -->  
          <el-button @click="SeeCourse(courses1,scope.$index)" type="text" size="small">&nbsp;&nbsp;&nbsp;观看课程&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</el-button>   
          <!-- 取消收藏按钮，点击时调用cancelFavorite方法，传入课程ID -->  
          <el-button type="text" size="small" @click="cancelFavorite(scope.row.id)">取消收藏&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</el-button>  
        </template>  
      </el-table-column>  
    </el-table>  
  </el-tab-pane>  
  
  <!-- 第二个标签页，标签为"上传的课程" -->  
  <el-tab-pane label="上传的课程">  
    <!-- 表格组件，展示上传的课程数据，宽度100% -->  
    <el-table :data="courses2" style="width: 100%">  
      <!-- 课程分类列 -->  
      <el-table-column prop="categoryName" label="课程分类"></el-table-column>  
      <!-- 课程名称列 -->  
      <el-table-column prop="courseName" label="课程名称"></el-table-column>  
      <!-- 课程教师列 -->  
      <el-table-column prop="lecturerName" label="课程教师"></el-table-column>  
      <!-- 课程简介列 -->  
      <el-table-column prop="introduce" label="课程简介"></el-table-column>  
      <!-- 价格列 -->  
      <el-table-column prop="coursePrice" label="价格(元)"></el-table-column>  
      <!-- 课程状态列，根据isPutaway的值显示已上架或待审核 -->  
      <el-table-column prop="isPutaway" label="课程状态">  
        <template slot-scope="scope">  
          {{ scope.row.isPutaway ? '已上架' : '待审核' }}  
        </template>  
      </el-table-column>  
      
          <!-- 添加操作列 -->
          <el-table-column label="操作" width="120">
            <template slot-scope="scope">  
    <!-- 观看课程按钮，点击时调用SeeCourse方法，传入当前表格的数据源courses2和当前行的索引（但通常更推荐传入当前行的数据scope.row） -->  
    <el-button @click="SeeCourse(scope.row)" type="text" size="small">&nbsp;&nbsp;&nbsp;观看课程&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</el-button>  
    <!-- 修改课程按钮，点击时调用editCourse方法，同样建议传入scope.row而非courses2和索引 -->  
    <el-button @click="editCourse(scope.row)" type="text" size="small">修改课程&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</el-button>  
    <!-- 删除课程按钮，点击时调用deleteCourse方法，传入当前行的id、logoName和objectName -->
    <el-button @click="deleteCourse(scope.row.id, scope.row.logoName, scope.row.objectName)" type="text" size="small">删除课程&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</el-button>  
  </template>  
          </el-table-column>
          
        </el-table>
      </el-tab-pane>

      <el-tab-pane label="上传课程">
        <div class="container">
          <div class="upload">
            <h2>上传课程</h2>
            <br>
             <!-- 表单，提交时阻止默认行为，调用uploadCourse方法 -->  
      <form @submit.prevent="uploadCourse" class="text">  
        <!-- 下拉选择框，用于选择课程分类 -->  
        <el-select v-model="value" placeholder="请选择课程分类">  
          <el-option  
              v-for="item in options"  
              :key="item.value"  
              :label="item.label"  
              :value="item.value">  
          </el-option>  
        </el-select>  
        <br><br>  
        <!-- 教师名称输入框 -->  
        <input type="text" v-model="lecture_name" placeholder="教师名称" required><br><br>  
        <!-- 课程名称输入框 -->  
        <input type="text" v-model="course_name" placeholder="课程名称" required><br><br>  
        <!-- 课程介绍输入框 -->  
        <input type="text" v-model="introduce" placeholder="课程介绍" required><br>  
        <!-- 课程logo上传区域 -->  
              <p>点击+上传课程logo</p>
<el-upload class="avatar-uploader"
           :action="getUploadUrl()"
           :show-file-list="false"
           :on-success="handleAvatarSuccess">
    <img v-if="course_logo" :src="course_logo" class="avatar">
    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>

              <el-divider content-position="center"></el-divider>
              <p>请选择是否收费</p>
              <div>
                <el-radio v-model="is_free" label="1">免费</el-radio>
                <el-radio v-model="is_free" label="0">收费</el-radio>
                <el-alert
                    v-if="is_free === '1'"
                    title="感谢您的贡献"
                    type="success"
                    show-icon>
                </el-alert>
                <div v-if="is_free === '0'">
                  <el-input
                      placeholder="请输入课程价格(元)"
                      v-model="course_price"
                      :disabled="false">
                  </el-input>
                </div>
              </div>
              <el-divider content-position="center"></el-divider>
              <p>请选择上传的课程</p>
              <br>
              <div class="filebotton">
                <input type="file" accept="video/*" capture="camcorder" @change="handleFileUpload"/>
              </div>
              <br>
              <button style="display: block; margin: 0 auto;" type="button" @click="uploadFile">上传课程视频</button>
              <br>
              <button style="display: block; margin: 0 auto;" type="button" @click="uploadCourse">上传课程信息</button>


            </form>
          </div>
        </div>
      </el-tab-pane>


    </el-tabs>
  </div>
</template>

<script>
import axios from 'axios'
import {Toast} from 'vant';

export default {
  data() {
    return {
      selectedFile: null,
      courseId: '',
      lecture_name: '',
      course_name: '',
      introduce: '',
      is_free: '',
      course_price: '',
      objectName: '',
      course_logo:'',
      logo_name:'',
      value: '',
      username: '',
      imageUrl: '',
      options: [
        {value: '计算机科学', label: '计算机科学'},
        {value: '数学', label: '数学'},
        {value: '历史', label: '历史'},
        {value: '生物学', label: '生物学'},
        {value: '文学', label: '文学'},
        {value: '舞蹈', label: '舞蹈'},
        {value: '音乐', label: '音乐'},
        {value: '游戏教程', label: '游戏教程'},
        {value: '其他', label: '其他'},
      ],

      tabPosition: 'top',
      courses1: [],
      courses2: [],
    };
  },
  methods: {
    goBack() {
      this.$router.go(-1);
    },
    // 获取用户自己收藏的课程
    fetchFavorite() {
      const userNameJson = localStorage.getItem("user") || '';
      const userNameData = JSON.parse(userNameJson);
      this.username = userNameData.username;
      axios.post('http://localhost:8081/springboot01/course/listFavorite', {
            username: this.username,
          },
          {
            headers: {
              'Content-Type': 'application/json'
            }
          }
      )
          .then(response => {
            console.log('Response data:', response.data);
            if (response.data.msg === "请求成功!") {
              this.courses1 = response.data.data;
            }
          })
    },
// 获取用户战绩上传的课程
    fetchUpload() {
      const userNameJson = localStorage.getItem("user") || '';
      const userNameData = JSON.parse(userNameJson);
      this.username = userNameData.username;
      axios.post('http://localhost:8081/springboot01/course/fetchUpload', {
            username: this.username,
          },
          {
            headers: {
              'Content-Type': 'application/json'
            }
          }
      )
          .then(response => {
            console.log('Response data:', response.data);
            if (response.data.msg === "请求成功!") {
              this.courses2 = response.data.data;
            }
          })
    },

    cancelFavorite(id) {
      let favorites = JSON.parse(localStorage.getItem('favorites')) || [];

      
        // favorites 数组中移除
        const indexToRemove = favorites.indexOf(id);
        if (indexToRemove !== -1) {
          favorites.splice(indexToRemove, 1);
        } 

      localStorage.setItem('favorites', JSON.stringify(favorites));

      // 假设你已经从 localStorage 中获取了用户名
      const userNameJson = localStorage.getItem("user") || '';
      const userNameData = JSON.parse(userNameJson);
      this.username = userNameData.username;

      // 调用后端 API 更新收藏状态
      axios.post('http://localhost:8081/springboot01/course/deleteFavorite',
    {  
      username: this.username,  
      course_id: id  
    }, 
    {  
      headers: {  
        'Content-Type': 'application/json'  
      }  
    })  
    .then(response => {  
      console.log('Response data:', response.data);  
      if (response.data.success || response.data.msg === "请求成功!") {  
        Toast.success('取消收藏成功');  
      } else {  
        Toast.fail('操作失败');  
      }  
    })  
    .catch(error => {  
      console.error('Error:', error);  
      Toast.fail('网络请求失败');  
    }); 
    },
    getUploadUrl() {
      return `http://localhost:8081/springboot01/course/courseLogo`;
    },
    handleAvatarSuccess(response) {
      this.course_logo=response.data.courseLogo;
      this.logo_name=response.data.logoName;

      this.$toast("上传成功")
    },

    handleFileUpload(event) {
      this.selectedFile = event.target.files[0];

    },
    uploadFile() {
      const userNameJson = localStorage.getItem("user") || '';

      const userNameData = JSON.parse(userNameJson);
      this.username = userNameData.username;
      if (!this.selectedFile) {
        alert('请选择一个视频文件');
        return;
      }

      const formData = new FormData();
      formData.append('file', this.selectedFile);

      axios.post('http://localhost:8081/springboot01/file/uploadFile', formData)
          .then(response => {
            console.log(response.data.msg);
            if (response.data.code == "200") {
              this.objectName = response.data.data.msg
              alert('视频上传成功');
            } else {
              alert('视频上传失败');
              return;
            }

          })

    },
   uploadCourse() {
      if (!this.objectName) {
        alert("请先上传视频文件")
        return;
      }
      axios.post('http://localhost:8081/springboot01/course/uploadCourse',
          {
            objectName: this.objectName,
            username: this.username,
            lecturerName: this.lecture_name,
            categoryName: this.value,
            courseName: this.course_name,
            introduce: this.introduce,
            isFree: this.is_free,
            courseLogo:this.course_logo,
            logoName:this.logo_name,
            coursePrice: this.course_price,
          }, {
            headers: {
              'Content-Type': 'application/json'
            }
          })
          .then(responseCourse => {
            console.log('Course upload response:', responseCourse.data);
            if (responseCourse.data.msg === "请求成功!") {
              alert(responseCourse.data.msg);
            } else {
              // 处理课程信息上传失败的情况
              alert('课程信息上传失败');
            }
          })
          .catch(error => {
            console.error('Error during upload:', error);
            // 在这里处理错误情况，例如给用户适当的提示
            alert('上传过程中出现错误，请重试');
          });

    },
    SeeCourse(videos,id){
      this.$router.push(`/videoDetail?videos=${encodeURIComponent(JSON.stringify(videos[id]))}`);
    },
    editCourse(courses,id){
      this.$router.push(`/Course-edit?courses=${encodeURIComponent(JSON.stringify(courses[id]))}`);
    },
    deleteCourse(id,logo,object){
      axios.post('http://localhost:8081/springboot01/course/deleteCourse',
    {  
      id:id,
      objectName:object,
      logoName:logo  
    }, 
    {  
      headers: {  
        'Content-Type': 'application/json'  
      }  
    })  
    .then(response => {  
      console.log('Response data:', response.data);  
      if (response.data.msg === "请求成功!") {  
        Toast.success('删除成功');  
      } else {  
        Toast.fail('操作失败');  
      }  
    })  
    .catch(error => {  
      console.error('Error:', error);  
      Toast.fail('网络请求失败');  
    }); 
    },
  },
  mounted() {
    this.fetchUpload(); // 组件挂载后获取课程信息
    this.fetchFavorite();
  }
};
</script>
<style>

button {
  width: 10rem;
  height: 2.25rem;
  background-color: #ff9bad;
  color: white;
  border: none;
  border-radius: 3rem;
  font-size: 0.8em;
  font-weight: 700;
  cursor: pointer;
  transition: all .2s;
  position: relative;
  z-index: 1;
  overflow: hidden;
}

button:hover {
  color: #ff9bad;
}

button:after {
  content: "";
  background: white;
  position: absolute;
  z-index: -1;
  left: -20%;
  right: -20%;
  top: 0;
  bottom: 0;
  transform: skew(-45deg) scale(0, 1);
  transition: all 0.5s;
}

button:hover:after {
  transform: skew(-45deg) scale(1, 1);
}

.el-tabs {
  margin: 20px;
}

.upload {
  margin-bottom: 100px;
  text-align: center
}

.text {
  font-size: 20px;
}

.filebotton {
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 0 auto;
  border: 1px solid gray;
  width: 380px;
  border-radius: 4px;;
}

.container {
  width: 100%; /* 容器宽度为100%，也可以根据需要设置为具体的数值 */
  max-width: 600px; /* 容器最大宽度，可以根据需要调整 */
  max-height: 1000px;
  margin: 0 auto; /* 水平居中 */
  padding: 20px; /* 内边距，可以根据需要调整 */
  border: 1px solid #ccc; /* 添加边框样式 */
  border-radius: 8px; /* 添加圆角样式，可选 */
}

.avatar {
  width: 180px;
  height: 180px;
  border-radius: 50%;
  margin-bottom: 10px;
}
</style>